package action;

import global.Constants;
import global.beanUtils.BeanUtils;
import global.security.AuthenticatorHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import service.UserMetaService;
import service.UserService;
import util.MD5Utils;
import util.ServletHelp;
import util.StringUtils;
import domain.User;
import domain.UserMeta;

/**
 * 用户Action类.
 * <p>
 * 创建日期：2010-07-01<br>
 * 创建人：Xiyt<br>
 * 修改日期：<br>
 * 修改人：<br>
 * 修改内容：<br>
 * 
 * @author Xiyt
 * @version 1.0
 */
public class UserAction extends BaseAction {
	/**
	 * 用户Service
	 * */
	private UserService userService = null;
	/**
	 * 用户元数据Service
	 * */
	private UserMetaService userMetaService = null;

	/**
	 * @param userService
	 *            the userService to set
	 */
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/**
	 * @param userMetaService
	 *            the userMetaService to set
	 */
	public void setUserMetaService(UserMetaService userMetaService) {
		this.userMetaService = userMetaService;
	}

	/**
	 * 查询用户列表 带分页
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	@SuppressWarnings("unchecked")
	public ActionForward queryForPaging(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 参数设定
		Map map = request.getParameterMap();
		User paramUser = new User();
		BeanUtils.populate(paramUser, map);
		
		// 取得用户列表
		List<User> userList = new ArrayList<User>();
		JSONArray datas = new JSONArray();
		userList = userService.selectByCriteriaForPaging(paramUser);
		datas = JSONArray.fromObject(userList);
		int count = userService.countByCriteria(paramUser);

		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		res.put("datas", datas);
		res.put("results", count);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}

	/**
	 * 查询单个用户
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward getUser(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 用户ID
		String userId = request.getParameter("userId");

		// 取得用户
		User user = userService.selectByPrimaryKey(userId);

		// 取得用户
		JSONArray datas = new JSONArray();
		List<UserMeta> userMetaList = new ArrayList<UserMeta>();
		UserMeta paramUserMeta = new UserMeta();
		paramUserMeta.setUserId(userId);
		userMetaList = userMetaService.selectByCriteria(paramUserMeta);
		datas = JSONArray.fromObject(userMetaList);

		// 返回结果
		JSONObject res = JSONObject.fromObject(user);
		res.put("success", true);
		res.put("userMeta", datas);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}

	/**
	 * 保存用户
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	@SuppressWarnings("unchecked")
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		HttpSession session = request.getSession();
		// 参数设定
		Map map = ServletHelp.getParameterMap(request);
		map.put("session", session);

		// 更新用户信息
		JSONObject res = userService.update(map);

		// 返回结果
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}
	
	/**
	 * 修改密码
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	@SuppressWarnings("unchecked")
	public ActionForward changePwd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		boolean isSuccess = true;
		String errorMsg = "";

		HttpSession session = request.getSession();
		// 获得参数
		// 用户ID
		String userId = request.getParameter("userId");
		// 原密码
		String oldpassword = request.getParameter("oldpassword");
		// 新密码
		String password = request.getParameter("password");
		// 确认密码
		String repassword = request.getParameter("repassword");
		
		// 确认密码验证
		if(StringUtils.isEmpty(password) || StringUtils.isEmpty(repassword) || !password.equals(repassword)){
			isSuccess = false;
			errorMsg = Constants.E_REPASSWORD;
		}
		
		// 登录验证
		Map loginMap = userService.login(userId, oldpassword);
		if(!(Boolean)loginMap.get("success")){
			isSuccess = false;
			errorMsg = Constants.E_PASSWORD;
		}
		
		if(isSuccess){
			// 参数设定
			User paramUser = new User();
			if (StringUtils.isNotEmpty(userId)) {
				paramUser.setUserId(userId);
			}
			if (StringUtils.isNotEmpty(password)) {
				paramUser.setPassword(MD5Utils.getMD5String(password));
			}
			
			// 更新用户
			userService.update(paramUser);
			
			// 重新设置登录用户Session
			session.removeAttribute("CLIENT_SESSION");
			AuthenticatorHolder.closeClientSession();
		}
		
		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", isSuccess);
		res.put("message", errorMsg);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}

	/**
	 * 删除用户
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 用户ID
		String userIds = request.getParameter("userIds");
		// 删除用户
		if (StringUtils.isNotEmpty(userIds)) {
			String filePath = ServletHelp.getRealPath(request,Constants.FILE_PATH);
			userService.delete(userIds, filePath);
		}
		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}

	/**
	 * 更新用户状态
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	@SuppressWarnings("unchecked")
	public ActionForward updateStatus(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 用户ID
		String userIds = request.getParameter("userIds");
		// 状态
		String status = request.getParameter("status");
		// 更新用户状态
		if (StringUtils.isNotEmpty(userIds)) {
			Map map = new HashMap();
			map.put("status", status);
			userService.update(userIds, map);
		}
		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}
}
